<?php
class Registration
{
            
    private $db_connection = null;

    private $user_name = "";
    private $email = "";
    private $user_password = "";
    private $patente = "";
    private $direccion = "";
    private $user_password_hash = "";
    public  $registration_successful = false;
    public  $errors = array();
    public  $messages = array();

    public  function __construct()
    {
               
        if (isset($_POST["register"])) {
            $this->registerNewUser();
        }
    }

    private function registerNewUser()
    {
        $this->errors[] =  "<table style='float: right;'>";    
        if (empty($_POST['user_name'])) {

            $this->errors[] = "<tr><td>Usuario inv&aacute;lido.</td></tr>";
        } 
        if (empty($_POST['user_password']) || empty($_POST['re_password'])) {
            $this->errors[] = "<tr><td>Contrase&ntilde;a inv&aacute;lida.</td></tr>";
        } 
        
        if ($_POST['user_password'] !== $_POST['re_password']) {
            $this->errors[] = "<tr><td>Contrase&ntilde;a y repetici&oacute;n de contrase&ntilde;a no son iguales.</td></tr>";
        } 
        
        if (strlen($_POST['user_password']) < 6) {
            $this->errors[] = "<tr><td>Contrase&ntilde;a debe tener mas de 6 caracteres.</td></tr>";
        } 

        if (strlen($_POST['user_name']) > 64 || strlen($_POST['user_name']) < 2) {
            $this->errors[] = "<tr><td>Usuario debe tener mas de 2 caracteres.</td></tr>";
        } 

        if (!preg_match('/^[a-z\d]{2,64}$/i', $_POST['user_name'])) {
            $this->errors[] = "<tr><td>Ingrese usuario solamente con n&uacute;meros y letras.</td></tr>";
        } 

        if (empty($_POST['email'])) {
            $this->errors[] = "<tr><td>Email no puede ser vac&iacute;o.</td></tr>";
        } 

        if (strlen($_POST['email']) > 64) {
            $this->errors[] = "<tr><td>Email no puede tener mas de 64 caracteres.</td></tr>";
        } 

        if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $this->errors[] = "<tr><td>Email con formato inv&aacute;lido.</td></tr>";
        } 

        if (empty($_POST['patente'])) {
            $this->errors[] = "<tr><td>Patente inv&aacute;lida.</td></tr>";
        } 

        if (empty($_POST['direccion'])) {
            $this->errors[] = "<tr><td>Direcci&oacute;n inv&aacute;lida.</td></tr>";
        } 

        if (!empty($_POST['user_name'])
            && strlen($_POST['user_name']) <= 64
            && strlen($_POST['user_name']) >= 2
            && preg_match('/^[a-z\d]{2,64}$/i', $_POST['user_name'])
            && !empty($_POST['email'])
            && strlen($_POST['email']) <= 64
            && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
            && !empty($_POST['user_password'])
            && !empty($_POST['re_password'])
            &&  $_POST['user_password'] === $_POST['re_password']
            && !empty($_POST['patente'])
            && !empty($_POST['direccion'])
        ) {
              $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
             if (!$this->db_connection->connect_errno) {
                $this->user_name = $this->db_connection->real_escape_string(htmlentities($_POST['user_name'], ENT_QUOTES));
                $this->email = $this->db_connection->real_escape_string(htmlentities($_POST['email'], ENT_QUOTES));
                $this->patente = $this->db_connection->real_escape_string(htmlentities($_POST['patente'], ENT_QUOTES));
                $this->direccion =  $this->db_connection->real_escape_string(htmlentities($_POST['direccion'], ENT_QUOTES));
                $this->user_password = $_POST['user_password'];
                $this->user_password_hash = password_hash($this->user_password, PASSWORD_DEFAULT);
                $query_check_user_name = $this->db_connection->query("SELECT * FROM users WHERE user_name = '" . $this->user_name . "';");
                if ($query_check_user_name->num_rows == 1) {
                    $this->errors[] = "<tr><td>Usuario existente.</td></tr>";
                } else {
                    $query = "INSERT INTO users (user_name, user_password_hash, user_email,patente,direccion) 
                                   VALUES('".$this->user_name."','".$this->user_password_hash."','".$this->email."','".$this->patente."','".$this->direccion."');";
                    $query_new_user_insert = $this->db_connection->query($query);
                    if ($query_new_user_insert) {
                        $this->messages[] = "<tr><td>Cuenta creada exitosamente.</td></tr>";
                        $this->registration_successful = true;
                    } else {
                        $this->errors[] = "<tr><td>Ocurri&oacute; un error al registrarse, por intentelo de nuevo.</td></tr>";
                    }
                }
            } else {
                $this->errors[] = "<tr><td>No hay conexion a la base de datos.</td></tr>";
            }
        } else {
            $this->errors[] = "<tr><td>Error desconocido.</td></tr>";
        }

         $this->errors[] =  "</table>";
    }
}
?>